﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RulesCore
{

    class CompareRule : BaseRule
    {
        //ADD DIV IN 0 EXCEPTION
        //Properties
        private string Operator;
        private string Operand1;
        private string Operand2;
        private FormulaEvaluator eval = new FormulaEvaluator(); // For calculating expression
        private string  [] rulesplit;

        public CompareRule(string Rule)
        {
            this.rulesplit = Rule.Split(' ');
            this.Operand1 = rulesplit[0];
            this.Operand2 = rulesplit[2];
            this.Operator = rulesplit[1];
        }

        public override bool ChekRule()
        {
            
            if (IFint(this.Operand1))
            {
                return Resolved(eval.Evaluate(this.Operand1), this.Operator, eval.Evaluate(this.Operand2));
            }
            else
            {
                return Resolved(this.Operand1, this.Operator, this.Operand2);
            }
        }

        private bool IFint(string check)
        {
            try
            {
                eval.Evaluate(check);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// If the operands are strings
        /// </summary>
        /// <param name="Foperand"></param>
        /// <param name="op"></param>
        /// <param name="Soperand"></param>
        /// <returns></returns>
        private bool Resolved(string Foperand, string op, string Soperand)
        {
            if (Foperand.Equals(Soperand))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// If the operands are doubles
        /// </summary>
        /// <param name="Foperand"></param>
        /// <param name="op"></param>
        /// <param name="Soperand"></param>
        /// <returns></returns>
        private bool Resolved(double Foperand, string op, double Soperand)
        {
            switch (op)
            {
                case "<=": if (Foperand < Soperand || Foperand == Soperand) { return true; }
                    break;
                case ">=": if (Foperand > Soperand || Foperand == Soperand) { return true; }
                    break;
                case "=": if (Foperand == Soperand) { return true; }
                    break;
                case ">": if (Foperand > Soperand) { return true; }
                    break;
                case "<": if (Foperand < Soperand) { return true; }
                    break;
            }
            return false;
        } 
    }
}
